package com.hubing.cloud.app.web.config.minio;

import com.alibaba.fastjson2.JSONObject;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class MinioFileService {

    @Autowired
    MinioConfig minioConfig;

    /**
     * 文件上传至Minio
     */
    public JSONObject upload(MultipartFile file) {
        InputStream inputStream = null;
        //创建Minio的连接对象
        MinioClient minioClient = getClient();
        //获取存储桶
        String bucketName = minioConfig.getBucketName();
        try {
            inputStream = file.getInputStream();

            // Make bucketName bucket if not exist.
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called bucketName.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                log.info("Bucket " +"["+bucketName+ "]"+" already exists.");
            }

            // Uploads given stream as object in bucket.
            String oldFileName = file.getOriginalFilename();
            String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date())+ UUID.randomUUID().toString().replaceAll("-","")
                    +oldFileName.substring(oldFileName.lastIndexOf("."));
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                            inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            /**
             * 构建返回结果集
             */
            JSONObject ajax = new JSONObject();
            /**
             * 封装需要的数据进行返回
             */
            ajax.put("fileName", "/"+bucketName+"/"+objectName);
            ajax.put("url", "http://"+minioConfig.getEndpoint()+":"+minioConfig.getPort()+"/"+minioConfig.getBucketName()+"/"+objectName);
            return ajax;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally {
            //防止内存泄漏
            if (inputStream != null) {
                try {
                    inputStream.close(); // 关闭流
                } catch (IOException e) {
                    log.debug("inputStream close IOException:" + e.getMessage());
                }
            }
        }
    }

    public void downloadFile(String bucketName, String fileName, String downFileName) throws Exception {
        MinioClient minioClient = getClient();

        minioClient.downloadObject(DownloadObjectArgs.builder()
                .bucket(bucketName)
                // 要下载的文件的名字，多级目录则用"/"分割
                .object(fileName)
                // 下载后保存文件的路径,目录必须存在，不存在会抛异常，多级目录则写成test/test.txt,用/分割
                .filename(downFileName)
                .build());
        System.out.println("文件下载成功!");
    }


    /**
     * 提供一个获取Minio连接的方法
     * 获取Minio连接
     * @return
     */
    private MinioClient getClient(){
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint("http://"+minioConfig.getEndpoint()+":"+ minioConfig.getPort())
                        .credentials(minioConfig.getAccessKey(),minioConfig.getSecretKey())
                        .build();
        return minioClient;
    }
}

